package com.hnas.core.app_common.util;

import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnas.core.util.StringUtil;


@Component("initAppAction")
public class InitAppAction {

	@Value(value="#{component['termNo']}")
	private String termNo;//设备编号，唯一
	
	public  PostKey initApp(String url,CommonKeyData ckd) throws Exception {
		PostKey postKey = new PostKey();
		try {
			// log.info("开始初始化initApp");
			 ObjectMapper objectMapper = new ObjectMapper();
			 //加密类
			 AESTool aes = new AESTool();
			 SignatureUtil signatureUtil = new SignatureUtil();
			 
			 String appid = ckd.getAppid();//公司标识
			 String token = ckd.getToken();//令牌
			 String route = ckd.getRoute();//路由名称
			 String key = ckd.getKey();//加密key
//			 String termNo= GetMacAddr.getMac();//本机的设备编号，唯一
			 
			 //请求参数
			 DTORequest dtoRequest=new DTORequest();
			 dtoRequest.setAppid(appid);//APP标识
			 long millis = System.currentTimeMillis();
			 dtoRequest.setMillis(millis);//时间戳
			 String version="1.0.0";
			 dtoRequest.setVersion(version);//接口版本
			 dtoRequest.setRoute(route);//路由名称
			 dtoRequest.setToken(token);//令牌
			 dtoRequest.setTermNo(termNo);//设备编号
			 
			 //加密发送数据
//			 DTOApiInit dtoApiInit=new DTOApiInit();
//			 dtoApiInit.setAppid(appid);
//			 dtoApiInit.setTermNo(termNo);
//			 String sdatajson=objectMapper.writeValueAsString(dtoApiInit);//实体转json
//			 String sdata = aes.encrypt(sdatajson, key);//加密
			 
			 //发送数据赋值
			// dtoRequest.setSdata(sdata);
			 //数据签名
			 String lol="";//摘要
			 String sign = signatureUtil.generateSignature(appid, token, lol,millis);//签名
			 dtoRequest.setSign(sign);
			 //请求实体转json
			 String requestJson=objectMapper.writeValueAsString(dtoRequest);//实体转json
			 //pos数据
			 //发送 POST 请求
			  StringBuffer param=new StringBuffer();
			  param.append("dataType="+DataType.JSON);
			  param.append("&sendData="+URLEncoder.encode(requestJson,"UTF-8"));
			  //System.out.println("请求参数:"+param.toString());
			   //发送数据
			  String requestData=HttpRequest.sendPost(url,param.toString());
		      System.out.println("请求返回:"+requestData);
		      //json转为实体。
		      DTOApiResponse dtoResponse = new DTOApiResponse();
		      String resultData= "";
		      if(!requestData.equals("")){
		    	  dtoResponse=objectMapper.readValue(requestData, DTOApiResponse.class);
			      String code= dtoResponse.getCode();
			      String errMsg= dtoResponse.getErrMsg();
			      DTOResult dtoResult= dtoResponse.getResult();
			      String resultMsg= dtoResult.getResultMsg();
			      String resultcode= dtoResult.getResultCode();
			      resultData=dtoResult.getResultData();
		      }

		     
		      if(StringUtil.isNotEmpty(resultData)){
		    	  resultData = aes.decrypt(resultData, key);// 解密
			      postKey = JSON.parseObject(resultData, PostKey.class); 
		      }
		      DTOIfKeyvalidTime dto = new DTOIfKeyvalidTime();
		      dto.setValidtime(postKey.getValidTime());//获得返回的密钥有效时间
		      dto.setKeyvalue(postKey.getKey());//获得返回的密钥
		      Date date=new Date();
		      DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		      String time=format.format(date);
		      dto.setCreatetime(time);
		      System.out.println("初始化令牌1 === " + postKey.getToken());
		   // ifKeyvalidTimeService.saveKeyvalidTime(dto);
	        } catch (Exception e) {
	        	
	            e.printStackTrace();
	            System.out.println("初始化异常：" + e.getMessage());
	        }
		
		return postKey;
	}
}
